package com.chen.seckill.controller;

import com.alibaba.druid.util.StringUtils;
import com.chen.seckill.controller.vo.UserVO;
import com.chen.seckill.error.BusinessException;
import com.chen.seckill.error.EmBusinessError;
import com.chen.seckill.response.CommonReturnType;
import com.chen.seckill.service.bo.UserBO;
import com.chen.seckill.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

@Controller
@RequestMapping("/user")
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    // 用户登录接口
    @PostMapping("/login")
    @ResponseBody
    public CommonReturnType login(@RequestParam("telphone") String telphone,
                                  @RequestParam("password") String password) throws BusinessException {
        // 入参判空校验
        if (StringUtils.isEmpty(telphone) || StringUtils.isEmpty(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        // 用户登录服务，校验用户登录是否合法
        UserBO userBO = userService.validateLogin(telphone, DigestUtils.md5DigestAsHex(password.getBytes()));

        // 将登录凭证加入到用户登录成功的session中
        httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        httpServletRequest.getSession().setAttribute("LOGIN_USER", userBO);

        return CommonReturnType.create(null);
    }

    // 用户注册接口
    @PostMapping("/register")
    @ResponseBody
    public CommonReturnType register(@RequestParam("telphone") String telphone,
                                     @RequestParam("otpCode") String otpCode,
                                     @RequestParam("name") String name,
                                     @RequestParam("gender") Byte gender,
                                     @RequestParam("age") Integer age,
                                     @RequestParam("password") String password) throws BusinessException {
        // 验证手机号和对应的otpcode是否符合
        String inSessionOtpCode = (String) httpServletRequest.getSession().getAttribute(telphone);
        if (!StringUtils.equals(otpCode, inSessionOtpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不符合");
        }

        // 用户注册流程
        UserBO userBO = new UserBO();
        userBO.setName(name);
        userBO.setGender(gender);
        userBO.setAge(age);;
        userBO.setTelphone(telphone);
        userBO.setRegisterMode("byphone");
        userBO.setEncrpt_password(DigestUtils.md5DigestAsHex(password.getBytes()));

        userService.register(userBO);

        return CommonReturnType.create(null);
    }


    @PostMapping("/getotp")
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam("telphone") String telphone) throws BusinessException {
        // 需要按照一定规则生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);

        // 将对应的OTP验证码对应用户的手机号关联。使用httpsession的方式绑定手机号和otpcode
        httpServletRequest.getSession().setAttribute(telphone, otpCode);
        
        // 将OTP验证码通过短信通道发送给用户，暂且不做
        System.out.println("telphone = " + telphone + " & otpCode = "+ otpCode);

        return CommonReturnType.create(null);
    }

    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getUserById(@RequestParam("id") Integer id) throws BusinessException {
        UserBO userBO = userService.getUserById(id);

        if (userBO == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIT);
        }

        // 将核心领域模型用户对象转换为可供UI使用VO对象
        UserVO userVO = convertFromUserBO(userBO);
        // 返回通用对象
        return CommonReturnType.create(userVO);
    }

    public UserVO convertFromUserBO(UserBO userBO) {
        if (userBO == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userBO, userVO);
        return userVO;
    }

}
